package cqrtplm.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.dto.DspfStatusModuleitemDTO;
import cqrtplm.entity.DspfStatusModuleitemDO;
import cqrtplm.entity.DspfStatusModuleitemsubDO;
import cqrtplm.entity.DspfStatusModuleitemsubgroupDO;
import cqrtplm.mapper.DspfStatusModuleitemMapper;
import cqrtplm.mapper.DspfStatusModuleitemsubMapper;
import cqrtplm.mapper.DspfStatusModuleitemsubgroupMapper;
import cqrtplm.mapper.RtCfgStatusInfoMapper;
import cqrtplm.service.DspfStatusModuleitemService;
import cqrtplm.vo.ModuleitemTreeVO;
import cqrtplm.vo.TemplateInfoVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

import static cqrtplm.constant.RTTableTypeConstant.MODEL_IBA_TYPE;

/**
 * @author 博
 * @description 针对表【DSPF_Status_ModuleItem(DSPF_Status_ModuleItem)】的数据库操作Service实现
 * @createDate 2025-06-10 15:04:12
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DspfStatusModuleitemServiceImpl extends ServiceImpl<DspfStatusModuleitemMapper, DspfStatusModuleitemDO>
        implements DspfStatusModuleitemService {

    @Resource
    private DspfStatusModuleitemMapper dspfStatusModuleitemMapper;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private DspfStatusModuleitemsubMapper  dspfStatusModuleitemsubMapper;
    @Resource
    private RtCfgStatusInfoMapper rtCfgStatusInfoMapper;
    @Value("${STATUS_INFO_REFTYPE}")
    private String STATUS_INFO_REFTYPE;
    @Resource
    private DspfStatusModuleitemsubgroupMapper dspfStatusModuleitemsubgroupMapper; // 需要根据实际Mapper名称调整


    @Override
    public ResponseResult getDspfStatusModuleitemTree(DspfStatusModuleitemDTO dspfStatusModuleitemDTO) {
        List<DspfStatusModuleitemDO> dspfStatusModuleitemDOS = dspfStatusModuleitemMapper.selectByMoudleId(dspfStatusModuleitemDTO);

        if (dspfStatusModuleitemDOS == null || dspfStatusModuleitemDOS.isEmpty()) {
            TemplateInfoVO defaultTemplates = rtCfgStatusInfoMapper.getDefaultTemplateLatest(STATUS_INFO_REFTYPE,
                                                                                             MODEL_IBA_TYPE,
                                                                                             "通用机型默认模板");
            UserDO user = TyAccountContext.getUser();
            if (user == null) {
                return ResponseResult.fail("500", "用户信息为空");
            }
            String oid = String.valueOf(user.getOid());
            String name = user.getName();
            Date newDate = new Date();
            String moduleId = dspfStatusModuleitemDTO.getModuleId();
            if (StrUtil.isBlank(moduleId)){
                return ResponseResult.fail("500", "模块ID为空");
            }
            List<DspfStatusModuleitemDO> items = new ArrayList<>();
            List<DspfStatusModuleitemsubDO> subItems = new ArrayList<>();

            if (defaultTemplates != null && !dspfStatusModuleitemMapper.selectByMoudleId(
                    new DspfStatusModuleitemDTO(defaultTemplates.getModuleId())).isEmpty()) {
                // 如果存在默认模板，则复制该模板
                copyTemplateFromExisting(defaultTemplates, moduleId, oid, name, newDate, items, subItems);
            } else {
                // 如果不存在默认模板，则创建默认内容
                createDefaultTemplate(moduleId, oid, name, newDate, items, subItems);
            }

            // 执行批量插入
            boolean success = dspfStatusModuleitemMapper.insertByBatch(items);
            if (!success) {
                return ResponseResult.fail("500", "初始化分类项目失败");
            }
            boolean flag = dspfStatusModuleitemsubMapper.insertByBatch(subItems);
            if (!flag) {
                return ResponseResult.fail("500", "初始化分类项目内容失败");
            }

            // 将新创建的项添加到返回列表中
            dspfStatusModuleitemDOS.addAll(items);
        }

        // 构建返回的树形结构
        List<ModuleitemTreeVO> voList = buildModuleItemTreeVOList(dspfStatusModuleitemDOS);
        Map<String, List<ModuleitemTreeVO>> map = voList.stream()
                .collect(Collectors.groupingBy(ModuleitemTreeVO::getParentId));
        List<ModuleitemTreeVO> moduleitemTreeVOS = buildTree(map, "-1", dspfStatusModuleitemDOS);

        return ResponseResult.success(moduleitemTreeVOS);
    }

    /**
     * 从现有模板复制数据
     */
    private void copyTemplateFromExisting(TemplateInfoVO defaultTemplates, String newModuleId, String userId,
                                          String userName, Date createDate, List<DspfStatusModuleitemDO> items,
                                          List<DspfStatusModuleitemsubDO> subItems) {
        // 获取默认模板的数据
        DspfStatusModuleitemDTO defaultModuleItemDTO = new DspfStatusModuleitemDTO();
        defaultModuleItemDTO.setModuleId(defaultTemplates.getModuleId());
        List<DspfStatusModuleitemDO> defaultItems = dspfStatusModuleitemMapper.selectByMoudleId(defaultModuleItemDTO);

        // 创建ID映射关系，用于替换parentId
        Map<String, String> idMapping = new HashMap<>();
        idMapping.put("-1", "-1"); // 根节点保持不变

        // 先建立完整的ID映射关系
        for (DspfStatusModuleitemDO defaultItem : defaultItems) {
            String newId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
            idMapping.put(defaultItem.getItemId(), newId);
        }

        // 复制并更新item数据
        for (DspfStatusModuleitemDO defaultItem : defaultItems) {
            String newId = idMapping.get(defaultItem.getItemId());
            DspfStatusModuleitemDO newItem = new DspfStatusModuleitemDO();

            // 复制所有属性
            copyModuleItemProperties(defaultItem, newItem, newId, newModuleId, userId, userName, createDate);

            // 处理parentId映射
            String oldParentId = defaultItem.getParentId();
            String newParentId = idMapping.getOrDefault(oldParentId, oldParentId);
            newItem.setParentId(newParentId);

            items.add(newItem);
        }

        // 复制subItem数据
        // 用于存储sid映射关系 (oldSid -> newSid)
        Map<String, String> sidMapping = new HashMap<>();

        // 收集所有需要查询的itemId
        List<String> itemIds = defaultItems.stream()
                .map(DspfStatusModuleitemDO::getItemId)
                .collect(Collectors.toList());

        if (!itemIds.isEmpty()) {
            // 批量查询所有相关的subItem
            List<DspfStatusModuleitemsubDO> allSubItems = dspfStatusModuleitemsubMapper.selectByItemIds(itemIds);

            // 按itemId分组
            Map<String, List<DspfStatusModuleitemsubDO>> subItemsGroupedByItemId = allSubItems.stream()
                    .collect(Collectors.groupingBy(DspfStatusModuleitemsubDO::getItemId));

            // 处理每个defaultItem及其对应的subItems
            for (DspfStatusModuleitemDO defaultItem : defaultItems) {
                String oldItemId = defaultItem.getItemId();
                String newItemId = idMapping.get(oldItemId);

                // 获取该item对应的所有subItem
                List<DspfStatusModuleitemsubDO> oldSubItems = subItemsGroupedByItemId.getOrDefault(oldItemId, Collections.emptyList());

                // 复制每个subItem
                for (DspfStatusModuleitemsubDO oldSubItem : oldSubItems) {
                    DspfStatusModuleitemsubDO newSubItem = new DspfStatusModuleitemsubDO();
                    String newSid = String.valueOf(snowflakeIdComponent.getInstance().nextId());

                    // 复制所有属性
                    copyModuleItemSubProperties(oldSubItem, newSubItem, newSid, newModuleId, newItemId, userId, userName, createDate);
                    subItems.add(newSubItem);

                    // 记录sid映射关系
                    sidMapping.put(oldSubItem.getSid(), newSid);
                }
            }
        }

        // 复制群组信息
        copyModuleItemSubGroupInfo(defaultTemplates.getModuleId(), newModuleId, sidMapping, userId, userName, createDate);
    }


    /**
     * 复制RT_CFG_STATUSMODULEITEMSUBGROUP表中的群组信息
     */
    private void copyModuleItemSubGroupInfo(String oldModuleId, String newModuleId, Map<String, String> sidMapping,
                                            String userId, String userName, Date createDate) {
        // 如果没有sid映射关系，直接返回
        if (sidMapping.isEmpty()) {
            return;
        }

        // 批量查询所有需要复制的群组信息
        List<DspfStatusModuleitemsubgroupDO> oldGroupItems = dspfStatusModuleitemsubgroupMapper.selectByModuleId(oldModuleId);

        List<DspfStatusModuleitemsubgroupDO> newGroupItems = new ArrayList<>();
        for (DspfStatusModuleitemsubgroupDO oldGroupItem : oldGroupItems) {
            // 检查该groupItem对应的sid是否在映射中
            String newSid = sidMapping.get(oldGroupItem.getSid());
            if (newSid != null) {
                DspfStatusModuleitemsubgroupDO newGroupItem = new DspfStatusModuleitemsubgroupDO();
                // 复制属性
                copyModuleItemSubGroupProperties(oldGroupItem, newGroupItem, newSid, newModuleId, userId, userName, createDate);
                newGroupItems.add(newGroupItem);
            }
        }

        // 批量插入新的群组信息
        if (!newGroupItems.isEmpty()) {
            dspfStatusModuleitemsubgroupMapper.insertByBatch(newGroupItems);
        }
    }

    /**
     * 复制DspfStatusModuleitemsubgroupDO属性
     */
    private void copyModuleItemSubGroupProperties(DspfStatusModuleitemsubgroupDO source, DspfStatusModuleitemsubgroupDO target,
                                                  String newSid, String newModuleId, String userId, String userName, Date createDate) {
        // 生成新的主键ID
        target.setOid(snowflakeIdComponent.getInstance().nextId());
        target.setSid(newSid);
        target.setGroupId(source.getGroupId());
        target.setGroupName(source.getGroupName());
        target.setIsEdit(source.getIsEdit());
        target.setIsDisplayed(source.getIsDisplayed());
        target.setIsDelete(source.getIsDelete());
        target.setCreateTime(createDate);
        target.setCreateUserId(new BigInteger(userId));
        target.setCreateUsername(userName);
        target.setUpdateTime(null);
        target.setUpdateUserId(null);
        target.setUpdateUsername(null);
        target.setDeleteTime(null);
        target.setDeleteUserId(null);
        target.setDeleteUsername(null);
        target.setModuleId(newModuleId); // 设置新的moduleId
    }

    /**
     * 复制DspfStatusModuleitemDO属性
     */
    private void copyModuleItemProperties(DspfStatusModuleitemDO source, DspfStatusModuleitemDO target,
                                          String newItemId, String newModuleId, String userId, String userName, Date createDate) {
        target.setItemId(newItemId);
        target.setModuleId(newModuleId);
        target.setParentId(source.getParentId());
        target.setItemName(source.getItemName());
        target.setItemType(source.getItemType());
        target.setPositionNum(source.getPositionNum());
        target.setSortOrder(source.getSortOrder());
        target.setAuthorityRoleCode(source.getAuthorityRoleCode());
        target.setRemarks(source.getRemarks());
        target.setLvl(source.getLvl());
        target.setFSortCode(source.getFSortCode());
        target.setFDeleteMark(source.getFDeleteMark());
        target.setFEnabledMark(source.getFEnabledMark());
        target.setFDescription(source.getFDescription());
        target.setFCreateDate(createDate);
        target.setFCreateUserId(userId);
        target.setFCreateUserName(userName);
        target.setFModifyDate(null);
        target.setFModifyUserId(null);
        target.setFModifyUserName(null);
        target.setFDeleteDate(null);
        target.setItemCode(source.getItemCode());
//        target.setShortDescription(source.getShortDescription());
    }

    /**
     * 复制DspfStatusModuleitemsubDO属性
     */
    private void copyModuleItemSubProperties(DspfStatusModuleitemsubDO source, DspfStatusModuleitemsubDO target,
                                             String newSid, String newModuleId, String newItemId, String userId,
                                             String userName, Date createDate) {
        target.setSid(newSid);
        target.setItemId(newItemId);
        target.setModuleId(newModuleId);
        target.setDetailId(source.getDetailId());
        target.setSubType(source.getSubType());
        target.setDataItemCode(source.getDataItemCode());
        target.setPartsCode(source.getPartsCode());
        target.setPartsName(source.getPartsName());
        target.setDescrCode(source.getDescrCode());
        target.setDescrName(source.getDescrName());
        target.setIsOptional(source.getIsOptional());
        target.setSubName(source.getSubName());
        target.setDescrTypename(source.getDescrTypename());
        target.setDescrTypeCode(source.getDescrTypeCode());
        target.setDescrValueCode(source.getDescrValueCode());
        target.setProductClass(source.getProductClass());
        target.setDefaultValue(source.getDefaultValue());
        target.setDefaultText(source.getDefaultText());
        target.setSortOrder(source.getSortOrder());
        target.setNotFromBom(source.getNotFromBom());
        target.setFSortCode(source.getFSortCode());
        target.setFDeleteMark(source.getFDeleteMark());
        target.setFEnabledMark(source.getFEnabledMark());
        target.setFDescription(source.getFDescription());
        target.setFCreateDate(createDate);
        target.setFCreateUserid(userId);
        target.setFCreateUserName(userName);
        target.setFModifyDate(null);
        target.setFModifyUserId(null);
        target.setFModifyUserName(null);
        target.setFixValue(source.getFixValue());
        target.setFixText(source.getFixText());
        target.setSourceRange(source.getSourceRange());
        target.setEditByXMZ(source.getEditByXMZ());
        target.setEditByZTS(source.getEditByZTS());
        target.setFDeleteDate(null);
        target.setSubProjectLeader(source.getSubProjectLeader());
        target.setEditByPack(source.getEditByPack());
        target.setEditByDecal(source.getEditByDecal());
        target.setEditByElectric(source.getEditByElectric());
        target.setEditByDL(source.getEditByDL());
        target.setEditByJZ(source.getEditByJZ());
        target.setLinkPartCodes(source.getLinkPartCodes());
        target.setMapperName(source.getMapperName());
//        target.setAttributeIds(source.getAttributeIds());
    }

    /**
     * 创建默认模板
     */
    private void createDefaultTemplate(String moduleId, String oid, String name, Date newDate,
                                       List<DspfStatusModuleitemDO> items, List<DspfStatusModuleitemsubDO> subItems) {
        //0 同BOM  1 同机型  2 无限制
        // 如果不存在默认模板，则创建默认内容
        // 成品
        String cpId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(cpId,moduleId,"-1", "成品", 0, 10001, 0, 0, 1, newDate, oid, name));
        // 成品下级
        String dztsyqId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(dztsyqId,moduleId,cpId, "对状态室要求", 0, 10003, 1, 0, 1, newDate, oid, name));
        String rzyqId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(rzyqId,moduleId,cpId, "认证要求", 0, 10001, 1, 0, 1, newDate, oid, name));
        // 成品三级
        String rzyqxmId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(rzyqxmId,moduleId,rzyqId, "认证要求", 1, 10000, 2, 0, 1, newDate, oid, name));
        String bzfsId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(bzfsId,moduleId,dztsyqId, "包装方式", 1, 10005, 2, 0, 1, newDate, oid, name));
        subItems.add(new DspfStatusModuleitemsubDO(4,moduleId,rzyqxmId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),null,null,1,1,1,1,0,1,newDate,oid, name,String.valueOf(1),1,null,null,null,1,1,1,1,1,"ord_rz"));
        subItems.add(new DspfStatusModuleitemsubDO(7,moduleId,bzfsId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"附件单独打包需求","附件单独打包需求",1,0,2,0,0,1,newDate,oid, name,"",2,1,1,null,1,1,1,1,1,null));
        // 动力
        String dlId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(dlId,moduleId,"-1", "动力", 0, 10021, 0, 0, 1, newDate, oid, name));
        // 动力下级
        String kzxhId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(kzxhId,moduleId,dlId, "刻字型号", 0, 10003, 1, 0, 1, newDate, oid, name));
        String fdjxhId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(fdjxhId,moduleId,dlId, "发动机型号", 0, 10001, 1, 0, 1, newDate, oid, name));
        String csyqId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(csyqId,moduleId,dlId, "测试要求", 0, 10002, 1, 0, 1, newDate, oid, name));
        // 动力三级
        String kzxhxmId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(kzxhxmId,moduleId,kzxhId, "刻字型号", 1, 10001, 2, 0, 1, newDate, oid, name));
        String fdjxhxmId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(fdjxhxmId,moduleId,fdjxhId, "发动机型号", 1, 10001, 2, 0, 1, newDate, oid, name));
        String csyqxmId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(csyqxmId,moduleId,csyqId, "测试要求", 1, 10001, 2, 0, 1, newDate, oid, name));
        subItems.add(new DspfStatusModuleitemsubDO(5,moduleId,kzxhxmId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),null,null,1,0,1,1,0,1,newDate,oid, name,String.valueOf(1),1,null,null,null,0,1,1,1,1,null));
        subItems.add(new DspfStatusModuleitemsubDO(3,moduleId,fdjxhxmId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),null,null,1,0,2,1,0,1,newDate,oid, name,String.valueOf(1),1,null,null,null,0,1,1,1,1,null));
        subItems.add(new DspfStatusModuleitemsubDO(6,moduleId,csyqxmId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),null,null,1,0,3,1,0,1,newDate,oid, name,String.valueOf(1),1,null,null,null,0,1,1,1,1,"TestDes"));

        // 机组
        String zjId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(zjId,moduleId,"-1", "机组", 0, 10039, 0, 0, 1, newDate, oid, name));
        // 机组下级
        String zjcsyqId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(zjcsyqId,moduleId,zjId, "机组测试要求", 0, 10001, 1, 0, 1, newDate, oid, name));
        // 组机三级
        String zjcsyqxmId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(zjcsyqxmId,moduleId,zjcsyqId, "机组测试要求", 1, 10001, 2, 0, 1, newDate, oid, name));
        subItems.add(new DspfStatusModuleitemsubDO(3,moduleId,zjcsyqxmId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),null,null,1,1,1,1,0,1,newDate,oid, name,String.valueOf(1),1,null,null,null,0,1,1,1,1,"TestDes"));
        // 其他
        String qtId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(qtId,moduleId,"-1", "其他", 0, 99999, 0, 0, 1, newDate, oid, name));
        String khtsyqId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(khtsyqId,moduleId,qtId, "客户特殊要求", 0, 10003, 1, 0, 1, newDate, oid, name));
        // 其他三级
        String tsyqId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        items.add(new DspfStatusModuleitemDO(tsyqId,moduleId,khtsyqId, "特殊要求", 1, 10003, 2, 0, 1, newDate, oid, name));
        subItems.add(new DspfStatusModuleitemsubDO(7,moduleId,tsyqId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"21","生产执行指令",0,null,3,null,0,1,newDate,oid, name,null,1,1,1,"动力组长审核,机组组长审核",0,0,1,1,1,"specialDes"));
        subItems.add(new DspfStatusModuleitemsubDO(7,moduleId,tsyqId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"唛头包装","唛头:包装",0,0,6,1,0,1,newDate,oid, name,"1",2,0,1,"状态室组长审核",1,0,0,0,0,"packLayout"));
        subItems.add(new DspfStatusModuleitemsubDO(7,moduleId,tsyqId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"技术要求","技术要求",0,0,4,1,0,1,newDate,oid, name,"1",2,1,1,"状态室组长审核",1,1,0,0,0,"otherRequested"));
        subItems.add(new DspfStatusModuleitemsubDO(7,moduleId,tsyqId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"附件单独打包方式","附件单独打包方式",0,0,9,1,0,1,newDate,oid, name,"1",2,0,1,"状态室组长审核",1,1,0,0,0,"separate_packing"));
        subItems.add(new DspfStatusModuleitemsubDO(7,moduleId,tsyqId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"附件单独打包方式","附件单独打包方式",0,0,8,0,0,1,newDate,oid, name,"",2,0,1,"状态室组长审核",1,1,0,null,null,"packaged_accessories"));
        subItems.add(new DspfStatusModuleitemsubDO(7,moduleId,tsyqId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"唛头说明书","唛头:说明书",0,0,7,1,0,1,newDate,oid, name,"1",2,0,1,"状态室组长审核",1,0,0,0,0,"explainBook"));
        subItems.add(new DspfStatusModuleitemsubDO(7,moduleId,tsyqId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"22","对状态室特殊要求",1,0,2,0,0,1,newDate,oid, name,"",2,1,0,"状态室组长审核",1,0,0,0,0,null));
        subItems.add(new DspfStatusModuleitemsubDO(7,moduleId,tsyqId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"唛头贴花","唛头:贴花",0,0,5,1,0,1,newDate,oid, name,"",2,1,0,"状态室组长审核",0,1,0,0,0,"appliqueLayout"));
        subItems.add(new DspfStatusModuleitemsubDO(7,moduleId,tsyqId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"20","产品特殊要求",1,0,1,1,0,1,newDate,oid, name,"1",2,0,0,"机组组长审核,动力组长审核,状态室组长审核",null,0,1,1,1,null));


        //需求状态表下移
        //客户编码
        subItems.add(new DspfStatusModuleitemsubDO(10,moduleId,tsyqId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"客户编码","客户编码",1,null,8,1,0,1,newDate,oid, name,"1",2,0,0,"",null,0,1,1,1,null));
       //样机类型
        subItems.add(new DspfStatusModuleitemsubDO(11,moduleId,tsyqId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"样机类型","样机类型",1,null,9,1,0,1,newDate,oid, name,"1",2,0,0,"",null,0,1,1,1,null));
        //产品用途
        subItems.add(new DspfStatusModuleitemsubDO(12,moduleId,tsyqId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"产品用途","产品用途",1,null,10,1,0,1,newDate,oid, name,"1",2,0,0,"",null,0,1,1,1,null));
        //客户动力备案型号
        subItems.add(new DspfStatusModuleitemsubDO(13,moduleId,tsyqId,String.valueOf(snowflakeIdComponent.getInstance().nextId()),"客户动力备案型号","客户动力备案型号",1,null,11,1,0,1,newDate,oid, name,"1",2,0,0,"",null,0,1,1,1,null));

    }

    private List<ModuleitemTreeVO> buildModuleItemTreeVOList(List<DspfStatusModuleitemDO> dspfStatusModuleitemDOS) {
        // 添加排序逻辑，例如按照 sortOrder 字段排序
        dspfStatusModuleitemDOS.sort(Comparator.comparing(DspfStatusModuleitemDO::getSortOrder));

        List<ModuleitemTreeVO> voList = new ArrayList<>();
        for (DspfStatusModuleitemDO doObj : dspfStatusModuleitemDOS) {
            ModuleitemTreeVO vo = new ModuleitemTreeVO();
            vo.setId(doObj.getItemId());
            vo.setParentId(doObj.getParentId());
            vo.setText(doObj.getItemName());
            vo.setValue(doObj.getItemId());
            vo.setLvl(doObj.getLvl());
            vo.setCheckstate(0);
            vo.setComplete(true);
            vo.setHasChildren(hasChildren(doObj.getItemId(), dspfStatusModuleitemDOS));
            vo.setIsexpand(true);
            vo.setShowcheck(false);
            vo.setTitle(null);
            vo.setItemType(doObj.getItemType());
            // 可根据需要设置扩展字段
            vo.setExt1(null);
            vo.setExt2(null);
            vo.setExt3(null);
            voList.add(vo);
        }
        return voList;
    }




    private boolean hasChildren(String id, List<DspfStatusModuleitemDO> dos) {
        return dos.stream().anyMatch(d -> d.getParentId() != null && d.getParentId().equals(id) );
    }

    private List<ModuleitemTreeVO> buildTree(Map<String, List<ModuleitemTreeVO>> map, String parentId, List<DspfStatusModuleitemDO> dos){
        List<ModuleitemTreeVO> children = map.getOrDefault(parentId, Collections.emptyList());

        for (ModuleitemTreeVO child : children) {
            child.setChildNodes(buildTree(map, child.getId(), dos));
        }
        return children;
    }


    @Override
    public ResponseResult deleteDspfStatusModuleByItemID(DspfStatusModuleitemDTO dspfStatusModuleitemDTO) {
        if (dspfStatusModuleitemDTO.getItemId() == null || dspfStatusModuleitemDTO.getItemId().isEmpty()) {
            return ResponseResult.fail("500","请选择要删除的项！");
        }
        boolean flag = dspfStatusModuleitemMapper.selectByItemID(dspfStatusModuleitemDTO.getItemId());
        if (flag){
            return ResponseResult.fail("500","子集不为空，请先删除子集后在进行删除操作！");
        }
        Long l = dspfStatusModuleitemMapper.deleteByItemID(dspfStatusModuleitemDTO.getItemId());
        if (l <= 0) {
            return ResponseResult.fail("500","删除失败！请刷新后再尝试！");
        }
        return ResponseResult.success("删除成功！");
    }

    @Override
    public ResponseResult getItemType(DspfStatusModuleitemDTO dspfStatusModuleitemDTO) {
        List<DspfStatusModuleitemDO> dspfStatusModuleitemDOS = dspfStatusModuleitemMapper.selectByMoudleIdAndItemType(dspfStatusModuleitemDTO);
        List<ModuleitemTreeVO> voList = new ArrayList<>();
        for (DspfStatusModuleitemDO doObj : dspfStatusModuleitemDOS) {
            ModuleitemTreeVO vo = new ModuleitemTreeVO();
            vo.setId(doObj.getItemId());
            vo.setParentId(doObj.getParentId());
            vo.setText(doObj.getItemName());
            vo.setValue(doObj.getItemId());
            vo.setLvl(doObj.getLvl());
            vo.setCheckstate(0);
            vo.setComplete(true);
            vo.setHasChildren(hasChildren(doObj.getItemId(), dspfStatusModuleitemDOS));
            vo.setIsexpand(true);
            vo.setShowcheck(false);
            vo.setTitle(null);

            // 可根据需要设置扩展字段
            vo.setExt1(null);
            vo.setExt2(null);
            vo.setExt3(null);

            voList.add(vo);
        }

        Map<String, List<ModuleitemTreeVO>> map = voList.stream()
                .collect(Collectors.groupingBy(ModuleitemTreeVO::getParentId));

        List<ModuleitemTreeVO> moduleitemTreeVOS = buildTree(map, "-1", dspfStatusModuleitemDOS);
        return ResponseResult.success(moduleitemTreeVOS);
    }

    @Override
    public ResponseResult insertDspfStatusModuleitem(DspfStatusModuleitemDO dspfStatusModuleitemDO) {
        // 获取当前登录用户信息
        UserDO user = TyAccountContext.getUser();
        dspfStatusModuleitemDO.setItemId(String.valueOf(snowflakeIdComponent.getInstance().nextId()));
        dspfStatusModuleitemDO.setFCreateDate(new Date());
        dspfStatusModuleitemDO.setFCreateUserId(String.valueOf(user.getOid()));
        dspfStatusModuleitemDO.setFCreateUserName(user.getName());
        Long l = dspfStatusModuleitemMapper.insertDspfStatusModuleitem(dspfStatusModuleitemDO);
        if (l <= 0) {
            return ResponseResult.fail("500","添加失败！请刷新后再尝试！");
        }
        return ResponseResult.success("添加成功！");
    }

    @Override
    public ResponseResult updateDspfStatusModuleitem(DspfStatusModuleitemDO dspfStatusModuleitemDO) {
        // 获取当前登录用户信息
        UserDO user = TyAccountContext.getUser();
        dspfStatusModuleitemDO.setFModifyDate(new Date());
        dspfStatusModuleitemDO.setFModifyUserId(String.valueOf(user.getOid()));
        dspfStatusModuleitemDO.setFModifyUserName(user.getName());
        Long l = dspfStatusModuleitemMapper.updateDspfStatusModuleitem(dspfStatusModuleitemDO);
        if (l <= 0) {
            return ResponseResult.fail("500","修改失败！请刷新后再尝试！");
        }
        return ResponseResult.success("修改成功！");
    }

    @Override
    public ResponseResult getDspfStatusModuleitemList(DspfStatusModuleitemDTO dspfStatusModuleitemDTO) {
        List<DspfStatusModuleitemDO> dspfStatusModuleitemList = dspfStatusModuleitemMapper.getDspfStatusModuleitemList(
                dspfStatusModuleitemDTO);
        return ResponseResult.success(dspfStatusModuleitemList);
    }

    @Override
    public List<DspfStatusModuleitemDO> selectByItemId(List<String> itemIds) {
        return dspfStatusModuleitemMapper.selectByItemId(itemIds);
    }

    @Override
    public List<DspfStatusModuleitemDO> selectByModuleId(String moduleId) {
        return dspfStatusModuleitemMapper.seelectByModuleId(moduleId);

    }


}





